<template>
  <div class="publish-page">
    <el-card>
      <template #header>
        <div class="header">
          <h2 class="title">发布问卷</h2>
        </div>
      </template>

      <!-- 问卷基本信息 -->
      <el-form label-width="100px" class="info-form">
        <el-form-item label="问卷标题">
          <span>{{ questionnaire.title }}</span>
        </el-form-item>
        <el-form-item label="问卷描述">
          <span>{{ questionnaire.description }}</span>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag :type="questionnaire.status === '0' ? 'info' : 'success'">
            {{ questionnaire.status === '0' ? '未发布' : '已发布' }}
          </el-tag>
        </el-form-item>
      </el-form>

      <el-divider />

      <!-- 发布设置 -->
      <el-form :model="publishForm" label-width="120px" ref="formRef" class="publish-form">
        <el-form-item label="发布范围" prop="scopes" required>
          <el-select v-model="publishForm.scopes" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3" filterable clearable placeholder="请选择发布范围" style="width: 300px;">
            <!-- 动态渲染后端返回的发布范围数据 -->
            <el-option
              v-for="scope in publishScopes"
              :key="scope.value"
              :label="scope.label"
              :value="scope.value"
            />
          </el-select>
          <el-popover placement="bottom" width="320" trigger="click">
            <template #reference>
              <el-link type="primary" style="margin-left: 8px;">查看已选({{ selectedScopeLabels.length }})</el-link>
            </template>
            <el-scrollbar style="max-height: 240px;">
              <el-tag v-for="(label, idx) in selectedScopeLabels" :key="idx" style="margin: 4px;" type="info">{{ label }}</el-tag>
              <div v-if="selectedScopeLabels.length === 0" style="padding: 8px 0; color: #909399;">暂无已选</div>
            </el-scrollbar>
          </el-popover>
        </el-form-item>


        <el-form-item label="发布时间" prop="startTime" required>
          <el-date-picker
            v-model="publishForm.startTime"
            type="datetime"
            placeholder="选择发布时间"
          />
        </el-form-item>

        <el-form-item label="截止时间" prop="endTime" required>
          <el-date-picker
            v-model="publishForm.endTime"
            type="datetime"
            placeholder="选择截止时间"
          />
        </el-form-item>

        <!-- <el-form-item label="是否匿名">
          <el-switch v-model="publishForm.anonymous" />
        </el-form-item> -->
      </el-form>

      <el-divider />

      <!-- 操作按钮 -->
      <div class="actions">
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" @click="confirmPublish">发布问卷</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const questionnaire = reactive({
  id: route.params.id,
  title: route.query.title || '未命名问卷',
  description: route.query.description || '暂无描述',
  status: route.query.status || '未发布',
  startTime: route.query.startTime || '',
  endTime: route.query.endTime || ''
})

const publishForm = reactive({
  scopes: [],
  startTime: '',
  endTime: '',
  anonymous: false
})

const publishScopes = ref([]) // 存储发布范围的选项
const formRef = ref(null)
const selectedScopeLabels = computed(() => {
  const map = new Map(publishScopes.value.map(i => [i.value, i.label]))
  return (publishForm.scopes || []).map(v => map.get(v)).filter(Boolean)
})


// 加载发布范围选项
const loadCompany = () => {
    request.get('/company/companyList').then(res => {
        // console.log('发布范围数据', res)
        if (res.status === 200) {
            publishScopes.value = res.data.data.map((scope) => ({
            label: scope.name,
            value: scope.id
            }))
        }
    })
}

// 发布前确认
const confirmPublish = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (!publishForm.scopes || publishForm.scopes.length === 0) {
        ElMessage.error('请至少选择一个发布范围')
        return
      }
      await ElMessageBox.confirm(
        '确定要发布该问卷吗？发布后问卷将可被用户填写。',
        '发布确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      handlePublish()
    } catch {
      ElMessage.info('已取消发布')
    }
  })
}

// 真正执行发布请求
const handlePublish = async () => {
  const params = {
    qid: questionnaire.id,
    compIds: publishForm.scopes,
    compId: Array.isArray(publishForm.scopes) ? publishForm.scopes.join(',') : '',
    startTime: publishForm.startTime,
    endTime: publishForm.endTime,
  }

  // console.log('tiaozhuancanshu',route.query)
  


  try {
    const res = await request.post('/questionnaire/asignQuestionnaire', params)
    if (res.status === 200) {
      ElMessage.success('发布成功')
      router.push({
        path: `/HomePage/GenerateQA/${params.qid}`,
        query: {
          title: route.query.title,
          description: route.query.description,
          status: '1',
          endTime: publishForm.endTime
        }
      })
    } else {
      ElMessage.error(res.msg || '发布失败')
    }
  } catch (err) {
    console.log('请求出错:', err)
    ElMessage.error('请求出错')
  }
}

const goBack = () => {
  router.push(`/HomePage/QuestionnaireList`)
}

onMounted(() => {
  loadCompany()
})
</script>

<style scoped>
.publish-page {
  background: #fff;
  padding: 30px 50px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header {
  text-align: center;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
}

.info-form,
.publish-form {
  margin-bottom: 20px;
}

.actions {
  text-align: center;
  margin-top: 30px;
}
</style>
